package com.koron.order.overhaul.notified;

import com.alibaba.fastjson.JSON;
import com.koron.common.core.util.CodeTools;
import com.koron.order.common.bean.base.OrderType;
import com.koron.order.common.bean.po.OrderInstructionBean;
import com.koron.order.common.bean.po.OrderLocationPo;
import com.koron.order.common.service.OrderInstructionService;
import com.koron.order.common.service.OrderLocationService;
import com.koron.order.overhaul.bean.convertor.OverhaulOrderConvertor;
import com.koron.order.overhaul.bean.vo.*;
import com.koron.order.overhaul.service.*;
import com.koron.order.overhaul.utils.CommonUtils;
import com.koron.order.overhaul.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author twcao
 * @title: OverhaulOrderDraft
 * @projectName GDH_EAM_V2
 * @description: 大修工单-草稿
 * @date 2021/10/811:34
 */
@Slf4j
@Component
public class OverhaulOrderDraft implements OverhaulOrderNotify<OverhaulOrderDraftVO> {

    @Autowired
    private OverhaulOrderService orderService;

    @Autowired
    private OverhaulOrderMajorService majorService;

    @Autowired
    private OverhaulOrderMajorFormService formService;

    @Autowired
    private OverhaulOrderReadyService readyService;

    @Autowired
    private OverhaulOrderItemService itemService;

    @Autowired
    private OverhaulOrderItemParamsService paramsService;

    @Autowired
    private OrderInstructionService instructionService;

    @Autowired
    private OverhaulOrderConvertor convertor;

    /*工单的工作地点*/
    @Autowired
    OrderLocationService orderLocationService;

    @Override
    public boolean execute(SessionFactory factory, OverhaulOrderDraftVO vo) {
        log.info("大修工单-草稿，vo = {}", JSON.toJSONString(vo));
        // 1、基本信息
        if(StringUtils.isNotBlank(vo.getTitle()) || StringUtils.isNotBlank(vo.getEquipmentId())) {
            orderService.saveOrUpdate(factory, vo);
        }
        // 2、专业初始化
        List<OverhaulOrderMajorVO> majors = vo.getMajors();
        if(CollectionUtils.isEmpty(majors)) {
           return true;
        }
        CommonUtils.sorted(majors);
        majors.stream().forEach(major -> {
            major.setId(StringUtils.isBlank(major.getId()) ? CodeTools.getCode32() : major.getId());
            major.setOverhaulId(vo.getId());
            CommonUtils.update(major);
            // 专业-表单
            List<OverhaulOrderMajorFormVO> forms = major.getForms();
            if(CollectionUtils.isNotEmpty(forms)) {
                CommonUtils.sorted(forms);
                forms.stream().forEach(form -> {
                    form.setId(StringUtils.isBlank(form.getId()) ? CodeTools.getCode32() : form.getId());
                    form.setOverhaulId(vo.getId());
                    form.setMajorId(major.getId());
                    CommonUtils.update(form);
                    // 专业-表单-作业准备
                    List<OverhaulOrderReadyVO> workReadys = form.getOverhaulReadies();
                    if(CollectionUtils.isNotEmpty(workReadys)) {
                        CommonUtils.sorted(workReadys);
                        workReadys.stream().forEach(ready -> {
                            ready.setId(StringUtils.isBlank(ready.getId()) ? CodeTools.getCode32() : ready.getId());
                            ready.setOverhaulId(vo.getId());
                            ready.setMajorId(major.getId());
                            ready.setFormId(form.getId());
                            CommonUtils.update(ready);
                        });
                    }
                    // 专业-表单-作业过程(嵌套列表，转成平铺列表)
                    form.setItemDTOs((List<OverhaulOrderItemVO>) CommonUtils.tileToList(form.getItemDTOs()));
                    List<OverhaulOrderItemVO> orderItems = form.getItemDTOs();
                    if(CollectionUtils.isNotEmpty(orderItems)) {
                        CommonUtils.sorted(orderItems);
                        orderItems.forEach(item -> {
                            CommonUtils.update(item, vo.getUpdateBy(), vo.getUpdateByName());
                            item.setId(StringUtils.isBlank(item.getId()) ? CodeTools.getCode32() : item.getId());
                            item.setOverhaulId(vo.getId());
                            item.setMajorId(major.getId());
                            item.setFormId(form.getId());
                            item.setParentId(StringUtils.isBlank(item.getParentId()) ? "0" : item.getParentId());
                            CommonUtils.update(item);
                            // 数据记录项（可能为空）
                            List<OverhaulOrderItemParamsVO> params = item.getItemParams();
                            if(CollectionUtils.isEmpty(params)) {
                                return;
                            }
                            CommonUtils.sorted(params);
                            params.stream().forEach(param -> {
                                param.setId(StringUtils.isBlank(param.getId()) ? CodeTools.getCode32() : param.getId());
                                param.setOverhaulId(vo.getId());
                                param.setMajorId(major.getId());
                                param.setFormId(form.getId());
                                param.setItemId(item.getId());
                                CommonUtils.update(param);
                            });
                        });
                    }
                });
            }
            // 表单-作业指导书
            List<OrderInstructionBean> instructions = major.getInstructions();
            if(CollectionUtils.isNotEmpty(instructions)) {
                Stream.iterate(0, i -> i + 1).limit(instructions.size()).forEach(i -> {
                    OrderInstructionBean instruction = instructions.get(i);
                    instruction.setId(StringUtils.isBlank(instruction.getId()) ? CodeTools.getCode32() : instruction.getId());
                    instruction.setBussinessId(major.getId());
                    instruction.setOrderType(OrderType.OVERHAUL);
                    instruction.setCreateTime(new Date());
                    instruction.setSort(i);
                });
            }
        });
        // 3、专业
        List<String> majorNames = majors.stream().map(major -> major.getMajorName()).filter(majorName -> !StringUtils.isBlank(majorName)).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(majorNames)) {
            majorService.deleteByOrderId(factory, vo.getId());
            majorService.saveOrUpdate(factory, convertor.majorVOsToBeans(majors));
        }
        // 4、专业-作业指导书
        List<OrderInstructionBean> instructions = majors.stream().filter(major -> CollectionUtils.isNotEmpty(major.getInstructions())).flatMap(major -> major.getInstructions().stream()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(instructions)) {
            majors.stream().forEach(major -> instructionService.deleteByBizId(factory, major.getId(), OrderType.OVERHAUL));
            instructionService.insertBatch(factory, instructions);
        }
        // 5、表单
        List<OverhaulOrderMajorFormVO> forms = majors.stream().flatMap(major -> major.getForms().stream()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(forms)) {
            formService.deleteByOrderId(factory, vo.getId());
            formService.saveOrUpdate(factory, convertor.formVOsToBeans(forms));
        }
        // 6、作业准备
        List<OverhaulOrderReadyVO> workReadies = forms.stream().flatMap(form -> form.getOverhaulReadies().stream()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(workReadies)) {
            readyService.deleteByOrderId(factory, vo.getId());
            readyService.saveOrUpdate(factory, convertor.readyVOsToBeans(workReadies));
        }
        // 7、作业过程
        List<OverhaulOrderItemVO> orderItems = forms.stream().flatMap(form -> form.getItemDTOs().stream()).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(orderItems)) {
            itemService.deleteByOrderId(factory, vo.getId());
            itemService.saveOrUpdate(factory, convertor.itemVOsToBeans(orderItems));
        }
        // 8、维护参数
        List<OverhaulOrderItemParamsVO> params = orderItems.stream().filter(item -> !CollectionUtils.isEmpty(item.getItemParams())).flatMap(item -> item.getItemParams().stream()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(params)) {
            paramsService.deleteByOrderId(factory, vo.getId());
            paramsService.saveOrUpdate(factory, convertor.paramVOsToBeans(params));
        }
        // 9、工作地点兼容之前的方式
        List<OrderLocationPo> orderLocationList = vo.getOrderLocationList();
        String location = vo.getLocation();
        String locationName = vo.getLocationName();
        if (!StringUtils.isAllEmpty(location,locationName)) {
            OrderLocationPo orderLocationPo = new OrderLocationPo();
            orderLocationPo.setLocation(location);
            orderLocationPo.setLocationName(locationName);
            orderLocationList.add(orderLocationPo);
        }
        if (CollectionUtils.isNotEmpty(orderLocationList)) {
            orderLocationList.forEach(p -> {
                p.setOrderId(vo.getId());
                p.setOrderType(OrderType.OVERHAUL);
            });
            orderLocationService.insertBatch(factory, orderLocationList);
        } else {
            orderLocationService.deleteByOrderId(factory, vo.getId());
        }

        return true;
    }

    @Override
    public int getOrder() {
        return 90000;
    }

    @Override
    public String status() {
        return Constants.OverhaulStatus.DRAFT;
    }
}
